package com.china.produce.aspect;

import com.china.produce.annotation.RequiresLogin;
import com.china.produce.annotation.RequiresPermissions;
import com.china.produce.annotation.RequiresRoles;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2023/3/3
 */
@Aspect
@Component
@Order(-4)
public class PreAuthorizeAspect {

    public PreAuthorizeAspect()
    {
    }

    /**
     * 切入使用注解的方法
     */
    public static final String POINTCUT_SIGN = " @annotation(com.china.produce.annotation.RequiresLogin) || "
            + "@annotation(com.china.produce.annotation.RequiresPermissions) || "
            + "@annotation(com.china.produce.annotation.RequiresRoles) ";

    @Pointcut(POINTCUT_SIGN)
    public void pointcut()
    {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable
    {
        // 注解鉴权
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        checkMethodAnnotation(signature.getMethod());
        try
        {
            // 执行原有逻辑
            Object obj = joinPoint.proceed();
            return obj;
        }
        catch (Throwable e)
        {
            throw e;
        }
    }

    public void checkMethodAnnotation(Method method)
    {
        // 校验@RequiresLogin注解
        RequiresLogin requiresLogin = method.getAnnotation(RequiresLogin.class);
        if (requiresLogin != null)
        {
           // AuthUtil.checkLogin();
        }

        // 校验@RequiresRoles注解
        RequiresRoles requiresRoles = method.getAnnotation(RequiresRoles.class);
        System.out.println(Arrays.asList(requiresRoles.value()));
        if (requiresRoles != null)
        {
           // AuthUtil.checkRole(requiresRoles);
        }

        // 校验@RequiresPermissions注解
        RequiresPermissions requiresPermissions = method.getAnnotation(RequiresPermissions.class);
//        if (requiresPermissions != null)
//        {
//           // AuthUtil.checkPermi(requiresPermissions);
//        }
    }


}
